package com.atguigu.leetcode;

import cn.hutool.core.lang.Console;
import org.junit.jupiter.api.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Notes
 * @Author gary
 * @Date 2021/11/4 13:44
 **/
public class _5LongestPalindrome {
    String s = "aacabdkacaa";

    @Test
    public void test() {
        String str = longestPalindrome(this.s);
        Console.log(str);
    }

    public String longestPalindrome(String s) {
        if (s.length() <= 1) {
            return s;
        }
        HashMap<Character, List<Integer>> map = new HashMap<>();
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            map.computeIfAbsent(c, ArrayList::new).add(i);
        }
        int max = 0;
        int left = 0;
        int right = 0;
        for (Map.Entry<Character, List<Integer>> characterListEntry : map.entrySet()) {
            List<Integer> value = characterListEntry.getValue();
            if (value.size() == 1) {
                continue;
            }
            int size = value.size();
            for (int i = 1; i < size; i++) {
                Integer r1 = value.get(i);
                Integer r2 = value.get(i - 1);
                int len = r1 - r2;
                if(len==1){
                    while (i+1<size&&(value.get(i+1)-r1)==1){
                        i++;
                        r1 = i;
                    }
                }

                if (len > max) {
                    max = len;
                    left = r2;
                    right = r1;
                }
            }
        }
        return s.substring(left,right+1);
    }
}
